//
//  YFLoginInAndUpVC.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/13.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//
#import "YFLoginInAndUpVC.h"
#import "YFCustomTextField.h"
#import <YYKit/YYKit.h>
#import "UIView+JCDrawTool.h"
#import "NSAttributedString+RichText.h"
#import "YFLoginApi.h"
#import "YFLoginHelper.h"
#import "YFWelcomePageController.h"
#import "YFUpheadIocnVC.h"
#import "YFAlertHelper.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "NSString+Extension.h"
#import "YFMMDrawerStateManager.h"
#import "JCError.h"
#import "WkWebView/WKWebviewController.h"
#import "JCTabBarViewController.h"

@interface YFLoginInAndUpVC ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet YFCustomTextField *emailTextfield;
@property (weak, nonatomic) IBOutlet YFCustomTextField *passwordTextfield;
@property (weak, nonatomic) IBOutlet UIButton *forgotPasswordBtn;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UILabel *threePartTipLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *privacyTopCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginInBtnTopCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginUpBtnTopCon;

@property (weak, nonatomic) IBOutlet UIView *perhapsView;
@property (weak, nonatomic) IBOutlet UIButton *faceBookBtn;
// 隐私协议
@property (weak, nonatomic) IBOutlet YYLabel *privacyLabel;
@property (weak, nonatomic) IBOutlet YYLabel *joinImmediatelyLabel;
@property (weak, nonatomic) IBOutlet UILabel *emailWrongTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *passwordWrongTipLabel;

// 是否开启边输入文字边校验
@property (nonatomic, assign)BOOL needEmailTimelyCheck;
@property (nonatomic, assign)BOOL needPasswordTimelyCheck;

@end

@implementation YFLoginInAndUpVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUI];
    [self changeToStyle:self.loginType animation:NO];
    self.emailTextfield.text = [User getUseInfo].email;
    
    __weak typeof(self) weakSelf = self;
    [self.emailTextfield setTextChangeHandler:^(NSString *text) {
        if (self.needEmailTimelyCheck) {
            [weakSelf showOrHiddenErrorTipLabel:[YFLoginHelper checkEmail:text] label:self.emailWrongTipLabel];
        }
    }];
    [self.passwordTextfield setTextChangeHandler:^(NSString *text) {
        if (self.needPasswordTimelyCheck) {
             [weakSelf showOrHiddenErrorTipLabel:[YFLoginHelper checkPassword:text userPredicate:YES] label:self.passwordWrongTipLabel];
        }
    }];
    
    [self.emailTextfield setTextFieldDidEndEidtHandler:^(NSString *text) {
        weakSelf.emailTextfield.rightButton.hidden = YES;
        if (text.length > 0){
            BOOL emailVaild = [YFLoginHelper checkEmail:text];
            weakSelf.needEmailTimelyCheck = !emailVaild;
            [weakSelf showOrHiddenErrorTipLabel:emailVaild label:self.emailWrongTipLabel];
        }
    }];
    [self.emailTextfield setTextFieldDidBenginEidtHandler:^(NSString *text) {
        weakSelf.emailTextfield.rightButton.hidden = NO;
    }];
    
    [self.passwordTextfield setTextFieldDidEndEidtHandler:^(NSString *text) {
        if (text.length > 0){
            BOOL passwordVaild = [YFLoginHelper checkPassword:text userPredicate:YES];
            weakSelf.needPasswordTimelyCheck = !passwordVaild;
            [weakSelf showOrHiddenErrorTipLabel:passwordVaild label:self.passwordWrongTipLabel];
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findPasswordCompleted:) name:@"FindPasswordCompleted" object:nil];
}
- (void)findPasswordCompleted:(NSNotification *)note {
    if (self.loginType == kLoginIn) {
        self.emailTextfield.text = note.object;
    }
}
// 显示和隐藏错误提示
- (void)showOrHiddenErrorTipLabel:(BOOL)hidden label:(UILabel *)label{
    /*
    UIColor *boderColor = hidden ? [UIColor whiteColor]:kTRedEEText;
    if ([label isEqual:self.emailWrongTipLabel]) {
        [self.emailTextfield changeCornerRadius:0 borderWidth:1 borderColor:boderColor];
    }else if ([label isEqual:self.passwordWrongTipLabel]){
        [self.passwordTextfield changeCornerRadius:0 borderWidth:1 borderColor:boderColor];
    }
     */
    [UIView animateWithDuration:0.35 animations:^{
        label.alpha = !hidden;
    } completion:^(BOOL finished) {
        label.hidden = hidden;
    }];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)loginBtnClick:(UIButton *)sender {
    [self loginOrRigiest:self.loginType email:self.emailTextfield.text andPassword:self.passwordTextfield.text];
}

// 邮箱登录和注册
- (void)loginOrRigiest:(kLoginType)loginType email:(NSString *)email andPassword:(NSString *)password {
    __weak typeof(self) weakSelf = self;
    [YFLoginHelper checkAccount:email password:password isChinese:NO complete:^(BOOL success, NSString *desc) {
        if (success) {
            RequestApiType apiType = loginType == kLoginIn ? kLoginEmailSignInApi:kLoginEmailSignUpApi;
            YFLoginApi *api = [YFLoginApi loginApiType:apiType email:email password:password];
            [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
            [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
                [weakSelf.view endEditing:YES];
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                if (success) {
                    if (loginType == kLoginIn) {
                        // 登录
                        NSDictionary *dict = [result responseInfo];
                        User *user = [User userWithPrivateKey:dict[@"ID"]];
                        UserInfoItem *infoItem = [UserInfoItem userInfoWithPrivateKey:user.userID];
                        [[RLMRealm defaultRealm] beginWriteTransaction];
                        user.isFirstLogin = [dict[@"IsFirstLogin"] boolValue];
                        user.token = dict[@"Token"];
                        infoItem.passWord = [password stringToMD5];
                        infoItem.email = email;
                        [[RLMRealm defaultRealm] commitWriteTransaction];
                        [YFUserDefaults saveLastLoginAccountID:dict[@"ID"]];
                        [YFUserDefaults setAutoLogin:YES];
                        // 配置缓存策略
                        [[YFNetworkingService sharedInstance] setUpRequestCacheFiltersWithUserId:user.userID];
                        if (user.isFirstLogin) {
                            YFWelcomePageController *welcomeVc = [[YFWelcomePageController alloc] init];
                            [weakSelf.navigationController pushViewController:welcomeVc animated:YES];
                        }else {
                            [YFLoginHelper getuserInfoItemCompleted:^(NSError *error) {
                                if (error == nil) {
                                    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                                    appdelegate.window.rootViewController = [[YFMMDrawerStateManager sharedManager] FetchDrawerController];
                                    appdelegate.window.rootViewController = [JCTabBarViewController new];
                                }
                            }];
                        }
                        
                    }else {
                        // 注册
                        [MBProgressHUD showSuccessHudInView:self.view message:@"Join now successfully" afterDelay:1.2];
                        // 切换到登录
//                        [weakSelf changeToStyle:kLoginIn animation:YES];
//                        weakSelf.passwordTextfield.text = nil;
                        // 直接登录
                        [weakSelf loginOrRigiest:kLoginIn email:email andPassword:password];
                    }
                }else {
                    [YFLoginHelper showFaultAlertViewWithMessage:error.domain onClick:^{
                        
                    }];
                    NSLog(@"%@",[error errorMessage]);
                }
            }];
        }else {
            [YFLoginHelper showFaultAlertViewWithMessage:desc onClick:^{
                
            }];
        }
    }];
}




/**
 Facebook登录
 */
- (IBAction)faceBookBtnClick:(UIButton *)sender {
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
//    if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"public_profile"]) {
//        [weakSelf dealWithFacebookUserID:[FBSDKAccessToken currentAccessToken].userID facebookToken:[FBSDKAccessToken currentAccessToken].tokenString];
//    }else{
        FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
        [login logInWithReadPermissions:@[@"public_profile"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:@"Process error" dimissAfterSecond:2];
            } else if (result.isCancelled) {
                [weakSelf.hud showErrorWithString:@"Cancelled" dimissAfterSecond:2];
            } else {
                [weakSelf dealWithFacebookUserID:result.token.userID facebookToken:result.token.tokenString];
            }
        }];
//    }
}

- (void)dealWithFacebookUserID:(NSString *)facebookUserID facebookToken:(NSString *)facebookToken{
    __weak typeof(self)weakSelf = self;
    [self getUserInfoWithFacebookUserID:facebookUserID complete:^(NSError *error, NSString *userID, NSString *firstName, NSString *lastName, Gender gender, NSString *url) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [YFLoginApi facebookLoginWithOpenID:userID accessToken:facebookToken gender:gender firstName:firstName lastName:lastName age:nil icon:url complete:^(NSError *error, NSString *userID, BOOL isFirstLogin, NSString *token) {
                if (error) {
                    [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                }else{
                    [weakSelf.hud dismiss];
                    User *user = [User userWithPrivateKey:userID];
                    UserInfoItem *infoItem = [UserInfoItem userInfoWithPrivateKey:user.userID];
                    [[RLMRealm defaultRealm] beginWriteTransaction];
                    user.isFirstLogin = isFirstLogin;
                    user.token = token;
                    infoItem.loginType = LoginTypeFacebook;
                    [[RLMRealm defaultRealm] commitWriteTransaction];
                    [YFUserDefaults saveLastLoginAccountID:user.userID];
                    [YFUserDefaults setAutoLogin:YES];
                    // 配置缓存策略
                    [[YFNetworkingService sharedInstance] setUpRequestCacheFiltersWithUserId:userID];
                    
                    if (user.isFirstLogin) {
                        YFWelcomePageController *welcomeVc = [[YFWelcomePageController alloc] init];
                        [weakSelf.navigationController pushViewController:welcomeVc animated:YES];
                    }else {
                        [YFLoginHelper getuserInfoItemCompleted:^(NSError *error) {
                            if (error == nil) {
                                AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                                appdelegate.window.rootViewController = [[YFMMDrawerStateManager sharedManager] FetchDrawerController];
                                appdelegate.window.rootViewController = [JCTabBarViewController new];
                            }else{
                                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                            }
                        }];
                    }
                }
            }];
        }
    }];
}

//获取用户信息 picture用户头像
- (void)getUserInfoWithFacebookUserID:(NSString *)facebookUserID complete:(void(^)(NSError *error, NSString *userID, NSString *firstName, NSString *lastName, Gender gender, NSString *url)) complete {
    NSDictionary *params =  @{@"fields":@"id,name,email,age_range,first_name,last_name,link,gender,locale,picture,timezone,updated_time,verified"};
    
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:facebookUserID
                                  parameters:params
                                  HTTPMethod:@"GET"];
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (error) {
            complete(error, nil, nil, nil, GenderUnknown, nil);
        }else{
            NSString *userID;
            NSString *firstName;
            NSString *lastName;
            Gender gender;
            NSString *url;
            userID = [NSString checkIfNullWithString:result[@"id"]];
            firstName = [NSString checkIfNullWithString:result[@"first_name"]];
            lastName = [NSString checkIfNullWithString:result[@"last_name"]];
            gender = [[NSString checkIfNullWithString:result[@"gender"]] isEqualToString:@"female"]?GenderFemale:GenderMale;
            url = [NSString checkIfNullWithString:result[@"picture"][@"data"][@"url"]];
            complete(nil, userID, firstName, lastName, gender, url);
        }
    }];
}

// 初始化UI
- (void)initializeUI {
    self.emailWrongTipLabel.hidden = YES;
    self.passwordWrongTipLabel.hidden = YES;
    self.emailWrongTipLabel.alpha = 0;
    self.passwordWrongTipLabel.alpha = 0;
    self.privacyLabel.backgroundColor = [UIColor clearColor];
    self.joinImmediatelyLabel.backgroundColor = [UIColor clearColor];
    self.loginInBtnTopCon.constant = (self.loginInBtnTopCon.constant * kYFScreenHeight / 667.0);
    self.loginUpBtnTopCon.constant = (self.loginUpBtnTopCon.constant * kYFScreenHeight / 667.0);
    [self.loginButton clipsCornerRadius:3];
    self.emailTextfield.showRightButton = YES;
    self.emailTextfield.rightButton.hidden = YES;
    [self.emailTextfield.rightButton setImage:[UIImage imageNamed:@"login_field_delete"] forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    [self.emailTextfield setClickRightButtonHandler:^(NSString *text) {
        weakSelf.emailTextfield.text = @"";
    }];
    
    self.passwordTextfield.delegate = self;
    self.emailTextfield.delegate = self;
    self.passwordTextfield.backgroundColor = [UIColor clearColor];
    self.emailTextfield.backgroundColor = [UIColor clearColor];
    [self.emailTextfield changeTextfieldStyle:LSTextfieldViewTypeEmail];
    [self.passwordTextfield changeTextfieldStyle:LSTextfieldViewTypePassword];
    [self.emailTextfield changeCornerRadius:0 borderWidth:1 borderColor:[UIColor whiteColor]];
    [self.passwordTextfield changeCornerRadius:0 borderWidth:1 borderColor:[UIColor whiteColor]];
    self.emailTextfield.placeHolderAlignment = NSTextAlignmentCenter;
    self.passwordTextfield.placeHolderAlignment = NSTextAlignmentCenter;
    self.emailTextfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Email" attributes:@{NSForegroundColorAttributeName:kTLightGray999}];
    self.passwordTextfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Password" attributes:@{NSForegroundColorAttributeName:kTLightGray999}];
    [self configueryy_LabelWithStyle:self.loginType];
    
}

- (void)configueryy_LabelWithStyle:(kLoginType)type {
    if (type == kLoginIn) {
        NSString *joinString = @"Not yet a member? Join now";
        [self configueryy_Label:self.joinImmediatelyLabel string:joinString hightlightStr:@"Join now"];
        NSString *privacyString = @"By logging in, you agree to Squash Spark's Privacy Policy.";
        [self configueryy_Label:self.privacyLabel string:privacyString hightlightStr:@"Privacy Policy."];
        
    }else {
        NSString *joinString = @"Already a member ? Sign in";
        [self configueryy_Label:self.joinImmediatelyLabel string:joinString hightlightStr:@"Sign in"];
        NSString *privacyString = @"By creating an account ,you agree to Squash Spark's Privacy Policy.";
        [self configueryy_Label:self.privacyLabel string:privacyString hightlightStr:@"Privacy Policy."];
    }
}

- (void)configueryy_Label:(YYLabel *)yy_label string:(NSString *)joinString hightlightStr:(NSString *)highlightStr {
    
    yy_label.displaysAsynchronously = YES;
    
    // 计算文本内容的大小
    NSRange joinrange = [joinString rangeOfString:highlightStr];
    NSMutableAttributedString *joinText = [[NSMutableAttributedString alloc] initWithString:joinString];
    joinText.font = kOpenSansFont(OpenSansRegular, 13);
    joinText.color = kTLightGray999;
    
    joinText.kern = @1.0;
    [joinText setUnderlineStyle:NSUnderlineStyleSingle];
    [joinText setUnderlineColor:[UIColor clearColor]];
    joinText.baselineOffset = @(2);
    
    if ([yy_label isEqual:self.joinImmediatelyLabel]) {
        joinText.alignment = NSTextAlignmentCenter;
    }else {
        joinText.alignment = NSTextAlignmentLeft;
    }
    [joinText setUnderlineColor:kTWhiteText range:joinrange];
    [yy_label sizeToFit];
    __weak typeof(self) weakSelf = self;
    [joinText setTextHighlightRange:joinrange color:kTWhiteText backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
         NSLog(@"%@--%@",containerView,text);
        BOOL isJoinLabel = [containerView isEqual:weakSelf.joinImmediatelyLabel];
        if (isJoinLabel) {
            [weakSelf changeToStyle:(weakSelf.loginType == kLoginIn ? kLoginUp:kLoginIn) animation:YES];
        }else {
            // 跳转隐私协议
            WKWebviewController *webVC = [[WKWebviewController alloc] init];
            webVC.urlString = kSettingPrivacyUrl;
            webVC.progressColor = kYellowGreenColor;
            [self.navigationController pushViewController:webVC animated:YES];
        }
        
    }];
    yy_label.attributedText = joinText;
}

//设定为某种风格
- (void)changeToStyle:(kLoginType)type animation:(BOOL)animation {
    if (self.loginType != type) {
        self.passwordTextfield.text = @"";
    }
    self.loginType = type;
    if (type == kLoginIn) {
        self.title = @"Sign In";
        [self.loginButton setTitle:@"LOG IN" forState:UIControlStateNormal];
        self.privacyTopCon.constant = 0;
        self.threePartTipLabel.text = @"Sign in with Facebook";
    }else if (type == kLoginUp){
        self.title = @"Join Now";
        [self.loginButton setTitle:@"CREATE ACCOUNT" forState:UIControlStateNormal];
        self.privacyTopCon.constant = -20;
        self.threePartTipLabel.text = @"Sign up with Facebook";
    }
    self.loginInBtnTopCon.priority = (type == kLoginUp) ? 333:999;
    self.loginUpBtnTopCon.priority = (type == kLoginUp) ? 999:333;
    [self configueryy_LabelWithStyle:type];
    if (animation){
        __weak typeof(self) weakself = self;
        self.joinImmediatelyLabel.alpha = 0;
        self.privacyLabel.alpha = 0;
        [UIView animateWithDuration:0.35 animations:^{
            [weakself.loginButton layoutIfNeeded];
            [weakself.view layoutIfNeeded];
//            weakself.joinImmediatelyLabel.alpha = (type == kLoginIn);
//            weakself.privacyLabel.alpha = (type == kLoginIn);
            weakself.joinImmediatelyLabel.alpha = 1;//(type == kLoginIn);
            weakself.privacyLabel.alpha = 1;//(type == kLoginIn);
            weakself.forgotPasswordBtn.alpha = (type == kLoginIn);
        } completion:^(BOOL finished) {
//            weakself.joinImmediatelyLabel.hidden = (type == kLoginUp);
//            weakself.privacyLabel.hidden = (type == kLoginUp);
            weakself.forgotPasswordBtn.hidden = (type == kLoginUp);
        }];
    }else {
//        self.joinImmediatelyLabel.hidden = (type == kLoginUp);
//        self.privacyLabel.hidden = (type == kLoginUp);
        self.forgotPasswordBtn.hidden = (type == kLoginUp);
    }
}

// 若是注册页面，密码框不让输入空格
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@" "] || [string isEqualToString:@"\n"]) {
        if ([textField isEqual:self.passwordTextfield] && self.loginType == kLoginUp) {
            return NO;
        }
    }
    return YES;
}


@end
